package model

import (
	app "im-demo/application"
)

// AddContact 添加联系人
func AddContact(ownerId, otherId string) error {
	ownerKey := getKey(ownerId)
	otherKey := getKey(otherId)
	ret := app.RedisClient.SAdd(ownerKey, otherId)
	if err := ret.Err(); err != nil {
		return err
	}
	ret = app.RedisClient.SAdd(otherKey, ownerId)
	if err := ret.Err(); err != nil {
		return err
	}

	return nil
}

// DelContact 删除联系人
func DelContact(key, member string) error {
	curKey := getKey(key)
	ret := app.RedisClient.SRem(curKey, member)
	return ret.Err()
}

// GetContacts 获取所有联系人
func GetContacts(key string) ([]User, error) {
	curKey := getKey(key)
	ret := app.RedisClient.SMembers(curKey)
	contacts, err := ret.Result()
	if err != nil {
		return nil, err
	}

	userList := make([]User, 0)
	for _, value := range contacts {
		user, err := GetUserInfo(value)
		if err != nil {
			continue
		}
		userList = append(userList, user)
	}

	return userList, nil
}

// getKey
func getKey(key string) string {
	return "contacts_" + key + "_set"
}
